package com.lei.msmservice.controller;

import com.lei.msmservice.service.MsmService;
import com.lei.msmservice.utils.RandomUtil;
import com.lei.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
@RestController
@RequestMapping("/edu/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信方法
    @GetMapping("send/{tel}")
    public Result smsSend(@PathVariable("tel") String tel){
        //从Redis里获取验证码
        String code = redisTemplate.opsForValue().get("yzm:" + tel);
        //如果有值就直接返回
        if (!StringUtils.isEmpty(code)){
            //逻辑上应该有问题: 当第一次发送失败的时候，第二次发送假如Redis有值就会造成用户体验差
            return Result.ok();
        }
        //生成验证码
        code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        //短信发送方法
        if (msmService.send(param,tel)){
            //设置有效时长5分钟
            redisTemplate.opsForValue().set("yzm:"+tel,code,5, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.error();
        }
    }
}
